<template>
  <div id="app">
    <div class="box">
      <div>
        <span>姓名:</span>
        <input type="text" v-model="username" />
      </div>
      <div>
        <span>年龄:</span>
        <input type="number" v-model="age" />
      </div>
      <div>
        <span>性别:</span>
        <select v-model="gender">
          <option value="男">男</option>
          <option value="女">女</option>
        </select>
      </div>
      <div>
        <button @click="add">添加/修改</button>
      </div>
    </div>
    <div>
      <table class="table table-bordered table-hover mt-2">
        <thead>
          <tr>
            <th>序号</th>
            <th>姓名</th>
            <th>年龄</th>
            <th>性别</th>
            <th>操作</th>
          </tr>
        </thead>

        <tbody>
          <tr v-for="(val, index) in arr" :key="val.id">
            <td>{{ val.id }}</td>
            <td>{{ val.username }}</td>
            <td>{{ val.age }}</td>
            <td>{{ val.gender }}</td>
            <td>
              <button @click="del(index)">删除</button>
              <button @click="edit(index)">编辑</button>
            </td>
          </tr>
        </tbody>
        <tfoot>
          <tr v-if="this.arr.length == 0">
            <td colspan="5" style="text-align: center">
              没有数据了,请添加数据
            </td>
          </tr>
        </tfoot>
      </table>
    </div>
  </div>
</template>
<script>
import "bootstrap/dist/css/bootstrap.css"; // 默认找文件夹下的index文件(但是这个不是所以需要写路径)

export default {
  data() {
    return {
      username: "",
      age: "",
      gender: "",
      idx: -1,
      // 读取本地若没有数据手动给一条
      arr: JSON.parse(localStorage.getItem("arr")) || [
        {
          id: 1,
          username: "老吴",
          age: 18,
          gender: "男",
        },
      ],
    };
  },
  mounted() {
    console.log(this.arr);
  },
  methods: {
    add() {
      if (this.idx != -1) {
        this.arr[this.idx].username = this.username;
        this.arr[this.idx].age = this.age;
        this.arr[this.idx].gender = this.gender;
      } else {
        this.arr.push({
          id: this.arr.length == 0 ? 1 : this.arr[this.arr.length - 1].id + 1,
          username: this.username,
          age: this.age,
          gender: this.gender,
        });
      }
      // 清空输入框
      this.username = "";
      this.age = "";
      this.gender = "";
      this.idx = -1;
    },
    edit(index) {
      // 回填
      this.username = this.arr[index].username;
      this.age = this.arr[index].age;
      this.gender = this.arr[index].gender;
      this.idx = index;
    },
    del(index) {
      this.arr.splice(index, 1);
    },
  },
  watch: {
    arr: {
      handler() {
        // 监听数组发生变化就添加进本地
        localStorage.setItem("arr", JSON.stringify(this.arr));
      },
    },
  },
};
</script>
<style scoped>
.box {
  display: flex;
  justify-content: center;
  align-items: center;
}
input {
  margin: 20px 20px;
}
select {
  margin: 20px 20px;
}
</style>